<template>
  <div class="pane-account">
    <el-form
      :model="account"
      :label-position="labelPosition"
      :rules="accountRules"
      label-width="auto"
      style="max-width: 600px"
      size="large"
      status-icon
      ref="formRef"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" show-password v-model="account.password" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormProps, FormRules, ElForm } from 'element-plus'
import { ElMessage } from 'element-plus'
import { LoginForm } from '@/types'
import { useLoginStore } from '@/store/login/login'
import { localCache } from '@/utils/cache'
const labelPosition = ref<FormProps['labelPosition']>('right')
// 定义account数据
const account = reactive<LoginForm>({
  name: localCache.getCache('name') || '',
  password: localCache.getCache('password') || ''
})
const accountRules: FormRules = {
  name: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    {
      // 最短4位，最长16位 {4,16}
      // 可以包含小写大母 [a-z] 和大写字母 [A-Z]
      // 可以包含数字 [0-9]
      // 可以包含下划线 [ _ ] 和减号 [ - ]
      pattern: /^[a-zA-Z0-9_-]{4,16}$/,
      message: '账号必须是4-16位',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{4,16}$/,
      message: '密码必须是4-16位大小写字母或数字的组合',
      trigger: 'blur'
    }
  ]
}

// 执行账号登录逻辑
const formRef = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()
function loginAction(isRemPwb: boolean) {
  // 官方组件写法
  // formRef.value?.validate((valid: boolean, errors: any)=>{
  //   if (valid) {
  //     console.log('登录成功')
  //   } else {
  //     ElMessage.error('Oops, 请输入正确格式的账号密码.')
  //   }
  // })
  formRef.value
    ?.validate()
    .then(() => {
      const name = account.name
      const password = account.password
      // 向服务器发送网络请求
      // accountLoginRequest({ name, password }).then((res) => {
      //   console.log(res)
      // })
      loginStore.loginAccountAction({ name, password }).then((res) => {
        if (isRemPwb) {
          // 记住密码
          localCache.setCache('name', name)
          localCache.setCache('password', password)
        } else {
          localCache.removeCache('name')
          localCache.removeCache('password')
        }
      })
      // .catch(() => {
      //   ElMessage.error('Oops, 登录失败.')
      // })
    })
    .catch(() => {
      ElMessage.error('Oops, 请输入正确格式的账号密码.')
    })
}
defineExpose({
  loginAction
})
</script>

<style lang="less" scoped>
.pane-account {
}
</style>
